package com.damocode.starter.yx.service.impl;

import com.damocode.starter.httpclient.domain.HttpResponse;
import com.damocode.starter.httpclient.exceptions.ClientException;
import com.damocode.starter.httpclient.helper.HttpClientHelper;
import com.damocode.starter.yx.autoconfigure.IMProperties;
import com.damocode.starter.yx.domain.HostType;
import com.damocode.starter.yx.domain.IMUser;
import com.damocode.starter.yx.http.YxUserRequest;
import com.damocode.starter.yx.service.IIMUserService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class IMUserService implements IIMUserService {

    private IMProperties imProperties;

    private HttpClientHelper httpClientHelper;

    public IMUserService(IMProperties imProperties, HttpClientHelper httpClientHelper) {
        this.imProperties = imProperties;
        this.httpClientHelper = httpClientHelper;
    }

    public String createUser(IMUser imUser) {
        String url = String.format(HostType.USER.getStrType(), "create.action");
        return doRequest(url, imUser);
    }

    public String createUser(String accid, String name, String icon) {
        IMUser imUser = new IMUser(accid, name, icon,"123456");
        return createUser(imUser);
    }

    public String updateUser(IMUser imUser) {
        String url = String.format(HostType.USER.getStrType(), "updateUinfo.action");
        return doRequest(url,imUser);
    }

    public String updateUser(String id, String name, String icon) {
        IMUser imUser = new IMUser(id, name, icon);
        return updateUser(imUser);
    }

    public String refreshToken(String accid) {
        String url = String.format(HostType.USER.getStrType(), "refreshToken.action");
        try {
            YxUserRequest yxUserRequest  = new YxUserRequest(url, imProperties.getAppKey(), imProperties.getAppSecret());
            yxUserRequest.setAccid(accid);
            HttpResponse httpResponse = httpClientHelper.syncInvoke(yxUserRequest);
            return httpResponse.getResponseText();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String doRequest(String url, IMUser imUser) {
        try {
            YxUserRequest yxUserRequest  = new YxUserRequest(url, imProperties.getAppKey(), imProperties.getAppSecret());
            yxUserRequest.setAccid(imUser.getAccid());
            yxUserRequest.setName(imUser.getName());
            yxUserRequest.setIcon(imUser.getIcon());
            yxUserRequest.setToken(imUser.getToken());
            HttpResponse httpResponse = httpClientHelper.syncInvoke(yxUserRequest);
            return httpResponse.getResponseText();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
